<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\tool\account\Account;
use think\facade\Cache;

class ContractBonusPool extends Base
{
    protected $name = 'contract_bonus_pool';

    public static $_type = [
        '1' => '银牌',
        '2' => '金牌',
        '3' => '钻石、金钻、黑金钻',
    ];

    public function getTypeTextAttr($value, $data): string
    {
        return isset(self::$_type[$data['type']]) ? self::$_type[$data['type']] : '';
    }

    public static function _save($param, $admin): array
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '记录不存在'];
            }

            if($info->total_amount != $param['total_amount']){
                BonusPoolEditLog::create([
                    'pool_id' => $info->id,
                    'old_amount' => $info->total_amount,
                    'new_amount' => $param['total_amount'],
                    'admin_id' => $admin['id'],
                    'admin_name' => $admin['admin_name'],
                    'create_time' => time()
                ]);
                $info->total_amount = $param['total_amount'];
                $info->save();
            }

            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 清空合约专区分红池  每月25号凌晨00:05执行
     * @return array
     */
    public static function clearPool(): array
    {
        parent::startTrans();
        try{
            $uids = self::getContractUids();
            $silver_uids = $uids[1];
            $gold_uids = $uids[2];
            $diamond_uids = $uids[3];

            ContractBonusPool::select()->each(function ($item) use ($silver_uids, $gold_uids, $diamond_uids){
                if(($item->id == 1 && $silver_uids) || ($item->id == 2 && $gold_uids) || ($item->id == 3 && $diamond_uids)){
                    BonusPoolEditLog::create([
                        'pool_id' => $item->id,
                        'old_amount' => $item->total_amount,
                        'new_amount' => 0,
                        'type' => 2
                    ]);
                    $item->actual_amount = $item->total_amount;
                    $item->total_amount = 0;
                    $item->save();
                }
            });

            parent::commit();
            return ['code' => 1, 'msg' => '合约专区分红池清空执行成功'];
        }catch (\Exception $e){
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 共享津贴分红
     * @return array
     */
    public static function poolBonus() :array
    {
        parent::startTrans();
        try {
            $silver_bonus = ContractBonusPool::where('id',1)->value('actual_amount');
            $gold_bonus = ContractBonusPool::where('id',2)->value('actual_amount');
            $diamond_bonus = ContractBonusPool::where('id',3)->value('actual_amount');

            $uids = self::getContractUids();
            $silver_uids = $uids[1];
            $gold_uids = $uids[2];
            $diamond_uids = $uids[3];

            if($silver_uids) self::shareBouns($silver_bonus, $silver_uids, 'silver');
            if($gold_uids) self::shareBouns($gold_bonus, $gold_uids, 'gold');
            if($diamond_uids) self::shareBouns($diamond_bonus, $diamond_uids, 'diamond');

            ContractBonusPool::update(['actual_amount'=>0], ['is_del'=>0]);
            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '共享津贴分红成功'];
    }

    public static function getContractUids(): array
    {
        $silver_uids = User::where(['is_del'=>0, 'is_lock'=>0])->where('contract_level_id', '>=', 1)->column('id');
        $gold_uids = User::where(['is_del'=>0, 'is_lock'=>0])->where('contract_level_id', '>=', 2)->column('id');
        $diamond_uids = User::where(['is_del'=>0, 'is_lock'=>0])->where('contract_level_id', '>=', 3)->column('id');

        return [1=>$silver_uids, 2=>$gold_uids, 3=>$diamond_uids];
    }

    /**
     * 共享津贴分红
     * @param $profit
     * @param $uids
     * @param $type
     */
    private static function shareBouns($profit, $uids, $type): bool
    {
        if($type == 'silver'){
            $cate = 1009;
            $note = '共享津贴银牌伙伴分红';
        }elseif($type == 'gold'){
            $cate = 1010;
            $note = '共享津贴金牌伙伴分红';
        }else{
            $cate = 1011;
            $note = '共享津贴钻石、金钻、黑金钻伙伴分红';
        }
        if($uids){
            /*$rate = Cache::get('system')['contract_share_'.$type.'_rate'];
            $share_sum = roundNum($profit * $rate, 2);*/
            $share_sum = $profit;
            $user_count = count($uids);
            $every_amount = roundNum($share_sum/$user_count, 2);

            if($every_amount>0){
                foreach ($uids as $uid){
                    Account::getInstance()->basics($uid, 'subsidy', $every_amount, $note, '+')->createBonus(0, $cate);
                }
            }
        }

        return true;
    }

}
